import React from 'react'
import { connect } from 'react-redux';
import { message, Button, Checkbox } from 'antd'
import './didi-expense.scss'
import { messages, deepFullCopy } from 'share/common';
import moment from 'moment'

class DDTransformPage extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      records: [],
      saveButtonLoading: false,
      selectedRelations: [], // 所有被选中的数据
      selectedRelationsIds: [], // 所有被选中的已拆分的Id
      selectedRecordIds: [], // 所有被全选的record
      selectedTotal: 0, // 入账币种的被选中的总金额
      isAll: false, //全选
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.records.length > 0 && nextProps.transformType && nextProps.showTransformPage) {
      let selectedRecordIds = deepFullCopy(this.state.selectedRecordIds)
      let selectedRelationsIds = deepFullCopy(this.state.selectedRelationsIds)
      let selectedRelations = deepFullCopy(this.state.selectedRelations)
      let selectedTotal = 0
      let temp = deepFullCopy(nextProps.records).map((record) => {
        let obj = {}
        let selectedRelationList = []
        obj.amount = record.companyRealPay
        obj.id = record.id
        obj.atlBankTransactionId = record.orderId
        record.notAssociated = obj
        record.selectedRelationList = selectedRelationList || []
        return record
      })
      this.setState({
        records: temp,
        selectedRecordIds,
        selectedRelationsIds,
        selectedRelations,
        selectedTotal,
      })
    }
  }

  handleOnClose = () => {
    this.setState({
      selectedRecordIds: [],
      selectedRelations: [],
      selectedRelationsIds: [],
      selectedTotal: 0,
      isAll : false,
    }, () => {
      this.props.hideSlide('transform')
    })
  }

  /**
   * 重置转因私或生成费用的金额选择页面
   */
  handleOnReset = () => {
    this.setState({
      selectedRecordIds: [],
      selectedRelations: [],
      selectedRelationsIds: [],
      selectedTotal: 0,
    })
  }


  /**
   * 格式化数字
   * @param {Number} nStr 数字
   */
  addCommas = (nStr) => {
    nStr = nStr + '';
    let x = nStr.split('.');
    let x1 = x[0];
    let x2 = x.length > 1 ? '.' + x[1] : '';
    let rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
  }

  /**
   * 金额被勾选触发
   */
  handleOnChecked = (e, line, record) => {

    console.log('e.target.checked', e.target.checked)
    console.log('line', line)
    let selectedRelations = deepFullCopy(this.state.selectedRelations)
    let selectedRelationsIds = deepFullCopy(this.state.selectedRelationsIds)
    let records = deepFullCopy(this.state.records)
    let allSelectedRecords = []
    if (e.target.checked) {
      if (!selectedRelationsIds.includes(line.id)) {
        selectedRelationsIds.push(line.id)
        selectedRelations.push(line)
      }
      allSelectedRecords = records.map((recordItem) => {
        if (recordItem.id === record.id) {
          recordItem.selectedRelationList.push(line)
        }
        return recordItem
      })
    } else {
      if (selectedRelationsIds.includes(line.id)) {
        selectedRelationsIds.splice(selectedRelationsIds.indexOf(line.id), 1)
        selectedRelations.some((relation, index) => {
          if (relation.id === line.id) {
            selectedRelations.splice(index, 1)
          }
        })
        allSelectedRecords = records.map((recordItem) => {
          if (recordItem.id === record.id) {
            recordItem.selectedRelationList.map((relationItem, relationIndex) => {
              if (relationItem.id === line.id) {
                recordItem.selectedRelationList.splice(relationIndex, 1)
              }
            })
          }
          return recordItem
        })
      }
    }
    let resultRelations = selectedRelations.filter((item) => item)
    let selectedTotal = (resultRelations && resultRelations.length > 0) ? resultRelations.map((relation) => relation.amount).reduce((total, num) => total + num) : 0
    this.setState({
      records: allSelectedRecords,
      selectedRelations: resultRelations,
      selectedRelationsIds,
      selectedTotal,
    })
  }

  handleOnTransform = async () => {
    if (!this.state.selectedRelations || this.state.selectedRelations.length === 0) {
      message.error('请先选择滴滴消费明细')
      return false
    }
    if (this.props.transformType === 2) { // 转因私
      const { selectedRelations, selectedTotal, records } = this.state
      if (selectedTotal <= 0) {
        message.error('转因私的所有滴滴消费总金额之和必须大于0')
        return false
      }
      let ids = this.state.selectedRelationsIds
      let relations = selectedRelations
      relations.map((item, index) => {
        relations[index] = {
          amount: item.amount,
          atlBankTransactionId: item.atlBankTransactionId,
          oriAmount: item.amount,
          oriCod: 'CNY'
        }
      })
      let params = {
        ids, relations
      }
      this.props.setInfo(selectedRelations, selectedTotal, params, records, this.handleOnReset)
    }
    this.setState({isAll : false})
  }

  handleChangeIsAll = (value) => {
    let selectedRelations = deepFullCopy(this.state.selectedRelations)
    let selectedRelationsIds = deepFullCopy(this.state.selectedRelationsIds)
    let records = deepFullCopy(this.state.records)
    let allSelectedRecords = []
    if(value){
      records.forEach(i=>{
        let line = i.notAssociated;
        let record = i;
        if (!selectedRelationsIds.includes(line.id)) {
          selectedRelationsIds.push(line.id)
          selectedRelations.push(line)
        }
        allSelectedRecords = records.map((recordItem) => {
          if (recordItem.id === record.id) {
            recordItem.selectedRelationList.push(line)
          }
          return recordItem
        })
      })
      let resultRelations = selectedRelations.filter((item) => item)
      let selectedTotal = (resultRelations && resultRelations.length > 0) ? resultRelations.map((relation) => relation.amount).reduce((total, num) => total + num) : 0
      this.setState({
        isAll: value,
        records: allSelectedRecords,
        selectedRelations: resultRelations,
        selectedRelationsIds,
        selectedTotal,
      });
    }else{
      this.setState({
        isAll: value,
        selectedRelations: [],
        selectedRelationsIds:[],
        selectedTotal: 0,
      });
    }
  };

  render() {
    const { selectedTotal, selectedRelationsIds, isAll } = this.state
    let records = deepFullCopy(this.state.records)
    return (
      <div>
        {records.map((record) => {
          return (
            <div className={'splitBlock'}>
              <div
                className={'blockHead'}
              >
                <div className='didiDetails'>
                  <span className={'headText'}>交易日期：</span>
                  <span className={'headText'}>{record.payTime ? moment(record.payTime).format('YYYY-MM-DD') : '-'}</span>
                </div>
                <div className='didiDetails'>
                  <span className={'headText'}>上车时间：</span>
                  <span className={'headText'}>{record.departureTime ? moment(record.departureTime).format('YYYY-MM-DD HH:mm:ss') : '-'}</span>
                  <span style={{ marginRight: '5px', marginLeft: '5px' }}>|</span>
                  <span className={'headText'}>下车时间：</span>
                  <span className={'headText'}>{record.finishTime ? moment(record.finishTime).format('YYYY-MM-DD HH:mm:ss') : '-'}</span>
                </div>
                <div className='didiDetails'><span className={'headText'}>上车地点：</span>
                  <span className={'headText'}>{record.actualStartName || '无'}</span></div>
                <div className='didiDetails'><span className={'headText'}>下车地点：</span>
                  <span className={'headText'}>{record.actualEndName || '无'}</span>
                </div>
              </div>
              <div className={'blockContent'}>
                {record.companyRealPay ? <div className={'contentHead'}>
                  {/** 待拆分金额的checkBox */}
                  <Checkbox
                    // disabled={!record.notAssociated.amount || Number(record.notAssociated.amount) === 0}
                    checked={selectedRelationsIds.includes(record.notAssociated.id)}
                    style={{ marginRight: '10px' }}
                    onChange={(e) => this.handleOnChecked(e, record.notAssociated, record)}
                  />
                  <span className={'contentBottomText'}>{'金额'}：</span>
                  {'CNY'
                    + ' ' + this.addCommas(Number(record.companyRealPay || '0').toFixed(2))}
                </div> : null}
              </div>
            </div>
          )
        })}
        <div className="slide-footer" >
          <Checkbox checked={isAll}
                    onChange={(e) => this.handleChangeIsAll(e.target.checked)}>
            {messages('request-4.key24')/*全选全部单据*/}
          </Checkbox>
          <span className={'totalText'}>
            {messages('mcd.myAccount.publicServiceCardBankBill.total')}
            {records.length > 0 && <span style={{ color: '#FA6478', fontSize: '12px' }}>{'CNY'} </span>}
            <span style={{ color: '#FA6478' }}>{this.addCommas(selectedTotal.toFixed(2))}</span>
          </span>
          <Button
            onClick={() => this.handleOnTransform()}
            loading={this.state.saveButtonLoading}
            type="primary"
            htmlType="submit"
          >
            {messages('supplier.key103')}
          </Button>
          <Button onClick={() => this.handleOnClose()}>{messages('common.cancel')}</Button>
        </div>
      </div>
    )
  }
}

DDTransformPage.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    company: state.login.company,
    user: state.login.user,
    loginUser: state.login.loginUser
  };
}
export default connect(mapStateToProps)(DDTransformPage);
